package cn.itcast.demo.task;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class HelloTask {

    @Autowired
    private RedissonClient redissonClient;

    @Scheduled(cron = "*/10 * * * * ?")
    public void job() throws InterruptedException {
        // 创建一个锁对象
        RLock lock = redissonClient.getLock("lock");
        log.info("尝试获取锁");
        // 开始获取锁
        boolean isLock = lock.tryLock(1, 1, TimeUnit.SECONDS);
        // 判断
        if(!isLock){
            log.error("获取锁失败，任务终止！");
            // 获取锁失败，结束
            return;
        }
        // 获取锁成功，开始执行任务
        try {
            log.info("获取锁成功，开始清理订单了！");
            Thread.sleep(500);
        } finally {
            // 释放锁
            log.warn("任务结束，准备释放锁！");
            lock.unlock();
        }
    }
}
